#!/bin/bash

cmd=(
	"GET /api/v2/dmp/get_crowd_list files/bilibili/dmp.json"
    "POST /api/v2/campaign/project/batch_query files/bilibili/camp_batch_query.json"
	"POST /api/v2/campaign/project/add files/bilibili/camp_add.json"
)

print_line() 
{
    local char="${1:-=}"
    local len="${2:-70}"
    char="${char:0:1}"

    # 检查 len 是否为正整数
    case "$len" in
        ''|*[!0-9]*) return ;;  # 包含非数字字符或为空 → 退出
    esac
    if ((len <= 0)); then
        return
    fi

    # 构造一行字符串（高效方式）
    local line=""
    local i
    for ((i = 0; i < len; i++)); do
        line+="$char"
    done
    printf '%s\n' "$line"
}

print_cmd_list() {
	print_line "-"
	echo "  API Commands List"
	print_line "-"
	for i in "${!cmd[@]}"; do
	    printf "%3d) %s\n" "$((i + 1))" "${cmd[i]}"
	done
	print_line "-"
}

# 手动执行媒体api接口
#set -- "GET" "/api/v2/dmp/get_crowd_list" "bilibili/dmp.json"
set -- "GET" "api/v2/report/realtime/get_data" "xiaomi/report/getDetailHourData.json"
./apipost.py "$@"
exit

if [ $# -gt 0 ]; then
    if [ $# -eq 3 ]; then
	    ./apipost.py "$@"
    else
        print_cmd_list
    fi
    exit $? 
fi

# CLI式执行媒体api接口
print_cmd_list
while true; do
    read -rp "Enter command number (1-${#cmd[@]}) or 'quit'/'exit': " choice

	# check for quit/exit (case-insensitive)
    case "${choice,,}" in
        q|quit|e|exit)
            echo "Bye!"
            exit 0
            ;;
    esac

	# check: 0
	if [[ "$choice" == 0 ]]; then
		print_cmd_list
		continue
	fi

    # Validate: must be a number in valid range
    if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#cmd[@]} )); then
        echo "[ERROR]: Enter a number between 1 and ${#cmd[@]}, or 'quit'/'exit'."
        continue
    fi

    # Execute selected command
    selected_cmd="${cmd[choice - 1]}"
	print_line "-" 60
    echo "./apipost.py $selected_cmd"
	./apipost.py $selected_cmd
done
